const arr = global.get("points");
if (!arr || arr.length === 0) return;

let startAddress = null;
let currentAddress = null;
let currentLength = null; // 新增：当前数据类型的长度（1或2）
let quantity = 0;
let values = [];
let currentTag = null;

// 创建DataView用于处理32位数据
const buffer = new ArrayBuffer(4);
const dataView = new DataView(buffer);

function sendWriteRequest(start, qty, vals, tag) {
    msg.payload = {
        value: vals,
        fc: 16, // 功能码16: 写多个寄存器
        unitid: 1,
        address: start,
        quantity: qty
    };
    msg.tag = tag;
    node.send(msg);
}

for (var i = 0; i < arr.length; i++) {
    const tag = arr[i];
    if ((tag[0] === '__NAME__' && tag[2] === '写')) {
        // 初始化未定义的变量
        if (typeof(global.get(tag[3])) == 'undefined') {
            global.set(tag[3], parseInt( tag[4] ) || 0); // 使用配置中的默认值
        }
        
        const address = parseInt(tag[1]);
        const dataType = tag[6];
        let value = global.get(tag[3]);
        let length = 1; // 默认长度
        
        // 根据数据类型处理值
        let registerValues = [];
        
        switch(dataType) {
            case 'bool':
                value = value ? 1 : 0;
                registerValues = [value];
                length = 1;
                break;
                
            case 'uint16':
                value = parseInt(value) || 0;
                registerValues = [value];
                length = 1;
                break;
                
            case 'int32':
                value = parseInt(value) || 0;
                dataView.setInt32(0, value, true); // 大端序
                registerValues = [
                    dataView.getUint16(0, true),
                    dataView.getUint16(2, true)
                ];
                length = 2;
                break;
                
            case 'float32':
                value = parseFloat(value) || 0;
                dataView.setFloat32(0, value, true); // 大端序
                registerValues = [
                    dataView.getUint16(0, true),
                    dataView.getUint16(2, true)
                ];
                length = 2;
                break;
                
            default:
                node.warn(`Unknown data type: ${dataType} for tag ${tag[3]}`);
                registerValues = [parseInt(value) || 0];
                length = 1;
        }
        
        // 如果是第一个元素或地址不连续或数据类型长度变化
        if (startAddress === null || 
            address !== currentAddress + currentLength ||
            length !== currentLength) {
            
            // 发送当前累积的数据
            if (startAddress !== null) {
                sendWriteRequest(startAddress, quantity, values, currentTag);
            }
            
            // 开始新的序列
            startAddress = address;
            currentAddress = address;
            currentLength = length;
            quantity = registerValues.length;
            values = [...registerValues];
            currentTag = tag;
        } else {
            // 地址连续且数据类型长度一致，添加到当前序列
            currentAddress = address + length - 1;
            quantity += registerValues.length;
            values.push(...registerValues);
            currentTag = tag;
        }
    }
}

// 发送最后一个序列
if (startAddress !== null) {
    sendWriteRequest(startAddress, quantity, values, currentTag);
}